package com.zjitc.backend_shop.interceptor;

import com.zjitc.backend_shop.utils.APIResponse;
import com.zjitc.backend_shop.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AdminInterceptor implements HandlerInterceptor {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("jwt");
        if (token != null) {
            Claims flag = JwtUtils.validateToken(token);
            if (flag != null) {
                return true;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        APIResponse apiResponse = new APIResponse<>();
        apiResponse.APIResponseError(2,"用户未登录或登录已过期",null);
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
        response.getWriter().print(jsonResponse);
        return false;
    }
}
